package cn.sunlight.mm.wx.controller;

import cn.sunlight.framework.annotation.HmComponent;
import cn.sunlight.framework.annotation.HmRequestMapping;
import cn.sunlight.framework.annotation.HmSetter;
import cn.sunlight.mm.base.BaseController;
import cn.sunlight.mm.common.GlobalConst;
import cn.sunlight.mm.entity.Result;
import cn.sunlight.mm.pojo.Course;
import cn.sunlight.mm.pojo.Dict;
import cn.sunlight.mm.utils.JedisUtils;
import cn.sunlight.mm.wx.service.CommonService;
import cn.sunlight.mm.wx.utils.LocationUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author sunlight
 * @description: 公共控制器
 * @date 2021/5/27
 * @Version v1.0
 */
@HmComponent
@Slf4j
public class CommonController extends BaseController {

    //初始化redis连接池
    static {
        JedisUtils.init(ResourceBundle.getBundle("jedis"));
    }

    @HmSetter("commonService")
    private CommonService commonService;

    /**
     * 根据参数获取数据
     *  fs 0 全部 1 首屏推荐
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/common/citys")
    public void getCitys(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            HashMap<String,Object> mapData = parseJSON2Object(request, HashMap.class);
            log.debug("data:{}",mapData);

            String cityName = LocationUtil.parseLocation((String) mapData.get("location"));

            Dict city =commonService.getCityInfoByName(cityName);
            List<Dict> cityList=commonService.getCityList((Integer)mapData.get("fs"));

            Map result = new HashMap<>();
            result.put("location",city);
            result.put("citys",cityList);

            // 需要特别注意，这里直接返回了result对象到客户端，是为了与前端代码一致。

            printResult(response,result);
        }catch (RuntimeException e){
            e.printStackTrace();
            log.error("getCitys",e);
            printResult(response,new Result(false,"获取失败"+e.getMessage()));
        }
    }

    /**
     * 获取学科列表
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/common/courseList")
    public void getCourseList (HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if(JedisUtils.isUsed()){
                log.debug("redis可用....");
                // 当redis可用时，获取Jedis对象
                Jedis jedis = JedisUtils.getResource();
                // 判断redis中是否有存储过学科列表数据
                String jsonString = jedis.get(GlobalConst.REDIS_KEY_WX_COURSE_LIST);
                if(jsonString == null || jsonString.length() == 0){
                    log.debug("redis可用....Redis中无数据...");
                    // 调用Service，获取数据，存入redis(以JSON字符串存入)
                    List<Course> courseList = commonService.findCourseList();
                    // [{},{},{}]
                    jedis.set(GlobalConst.REDIS_KEY_WX_COURSE_LIST,JSON.toJSON(courseList).toString());
                    // 返回JSON到客户端
                    printResult(response,new Result(true,"获取成功",courseList));
                }else{
                    log.debug("redis可用....Redis中有数据...(JSON String)");
                    printResult(response,new Result(true,"获取成功",JSON.parse(jsonString)));
                }
                jedis.close();
            }else{
                // 调用Service
                List<Course> courseList = commonService.findCourseList();
                // 返回JSON
                printResult(response,new Result(true,"获取成功",courseList));
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            log.error("getCourseList:{}",e);
            printResult(response,new Result(false,"获取失败"+e.getMessage()));
        }
    }

}
